import appService from '@/api/services/appService';
// import ChatBox from '@/pages/chat/components/ChatBox';
import ChatBox from '@/pages/app-qa/components/chat/components/ChatBox';
import ChatContextProvider, { ChatContext } from '@/pages/chat/context';
import { useParams } from '@/router/hooks';
import { ChatEventType, Message } from '@/types/chat';
import { useDebounceFn } from 'ahooks';
import { useEffect, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

interface Props {
  initChatId: string;
  initChatMessage: string;
  open: boolean;
  initAppId?: string;
  initShareId?: string;
}

const TestChatBox = ({ initChatId, initChatMessage, open, initAppId, initShareId }: Props) => {
  // chat
  const [list, setList] = useState<any[]>([]);
  const [listLeft, setListLeft] = useState<any[]>([]);
  const [isChatInitialized, setIsChatInitialized] = useState(false);
  const [historyMessages, setHistoryMessages] = useState<Message[]>([]);
  const { updateChatInfo, setAppInfo, event$ } = useContextSelector(ChatContext, (s) => s);
  const [did, setDid] = useState('');

  const { appId: id, shareId: share_id } = useParams() as { appId: string; shareId: string };

  const [appId, setAppId] = useState(initAppId || id);
  const [shareId, setShareId] = useState(initShareId || share_id);

  useEffect(() => {
    console.log('initAppId', initAppId);
    setAppId(initAppId || id);
  }, [initAppId]);

  const initChatBox = async () => {
    try {
      // const appResponse = await appService.appDetail(appId);
      // appResponse?.share_id && setShareId(appResponse.share_id);
      // if (appResponse?.dataset?.id) {
      //   setDid(appResponse.dataset.id);
      // }
      // setAppInfo(appResponse);
      updateChatInfo(appId, shareId, did);
    } catch (error) {
      // messageApi.error(error.message)
      // setTaskId('');
    }
  };

  const { run } = useDebounceFn(
    () => {
      event$?.emit({
        type: ChatEventType.SENDTEXT,
        data: initChatMessage,
      });
    },
    {
      wait: 500,
    },
  );

  useEffect(() => {
    setHistoryMessages([]);
  }, [initChatId, open]);

  useEffect(() => {
    setHistoryMessages([]);
    if (open === true) {
      run();
    }
  }, [open, initChatMessage]);

  useEffect(() => {
    initChatBox();
  }, []);

  return (
    <ChatBox
      isTest={true}
      initialMessages={historyMessages}
      initialQuestion={initChatMessage}
      // reHisList={() => {}}
      initChatId={initChatId}
      // setListLeft={setListLeft}
      // listLeft={listLeft}
      // setIsChatInitialized={setIsChatInitialized}
      // isChatInitialized={isChatInitialized}
      initAppId={appId}
      initShareId={shareId}
    />
  );
};

function Render({ ...props }: Props) {
  return (
    <ChatContextProvider>
      <TestChatBox {...props} />
    </ChatContextProvider>
  );
}

export default Render;
